//引入第三方模块mongoose
const mongoose = require('mongoose');
//引入Joi模块
const Joi = require('joi');
//设定集合规则
const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 20
  },
  email: {
    type: String,
    //保证邮箱地址唯一性
    unique: true,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  //normal 普通用户 admin 管理员
   role: {
     type: String,
     required: true
   },
  //0：启用  1：禁止
  state: {
    type: Number,
    default: 0
  }
})

//创建集合
const User = mongoose.model('User', userSchema);

//验证用户信息
const validateUser = user => {
  //定义对象的验证规则
  const schema = Joi.object({
    username: Joi.string().min(2).max(12).required().error(new Error('用户名不符合规则')),
    email: Joi.string().email(),
    password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/).required().error(new Error('密码不符合规则')),
    role: Joi.string().valid('normal','admin').required().error(new Error('角色值不符合规则')),
    state: Joi.number().valid(0,1).required().error(new Error('状态值不符合规则'))
  })
  //进行验证
  return schema.validate(user);
}

//将用户集合作为模块导出
module.exports = {
  User,
  validateUser
}
